package com.zut.edu.nfc;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qmuiteam.qmui.util.QMUIDisplayHelper;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUITopBarLayout;
import com.qmuiteam.qmui.widget.grouplist.QMUICommonListItemView;
import com.qmuiteam.qmui.widget.grouplist.QMUIGroupListView;
import com.zut.edu.R;
import com.zut.edu.bean.Lock;
import com.zut.edu.bean.Transport;
import com.zut.edu.bean.Page;
import com.zut.edu.http.BaseCallback;
import com.zut.edu.http.OkhttpHelper;
import com.zut.edu.utils.DESUtils;
import com.zut.edu.utils.StringUtils;
import com.zut.edu.widget.TimelineLayout;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

public class ShowTextActivity extends AppCompatActivity implements View.OnClickListener {

    private String data;
    private String mTagId;

    @BindView(R.id.showtext_topbar)
    QMUITopBarLayout showtexttopbar;
    @BindView(R.id.showtext_groupListView)
    QMUIGroupListView showtextgroupListView;
    @BindView(R.id.timeline_layout)
    TimelineLayout timelineLayout;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_showtext);
        ButterKnife.bind(this);
        QMUIStatusBarHelper.translucent(this);//沉浸式
        initTopBar();
        Intent intent = getIntent();
        data = intent.getStringExtra("data");
        mTagId = intent.getStringExtra("mTagId");
//        initGroupListView(data);
        getProductKey(mTagId);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
        }
    }

    private void initTopBar() {
        showtexttopbar.addLeftBackImageButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        showtexttopbar.setTitle("追溯结果");
    }

    private void getLog(String productId){
        OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();
        Map<String,Object> params = new HashMap<>(1);
        params.put("productId",productId);
        okhttpHelper.get(StringUtils.BASE_URL + "/log/query", params, new BaseCallback<Page<Transport>>() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }
            @Override
            public void onSuccess(@NotNull Call call, @NotNull Response response, Page<Transport> transportPage, int code) throws IOException {
                if(transportPage.getList()!=null){
                    initTimeLine(transportPage.getList());
                }

            }
            @Override
            public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {

            }
        });
    }

    private void initTime(int index,int sum,Transport transport){
        View view = LayoutInflater.from(this).inflate(R.layout.item_timeline, timelineLayout, false);

        ((TextView) view.findViewById(R.id.tv_action_time)).setText(transport.getLogDate());
        if(transport.getCompanyType().equals("4")){
            ((TextView) view.findViewById(R.id.tv_action)).setText(transport.getCompanyName()+"已于"+transport.getLogLocation()+"入库");
            ((TextView) view.findViewById(R.id.tv_action_status)).setText("完成");
        }
        else if(index==sum-1&&!transport.getCompanyType().equals("4")){
            ((TextView) view.findViewById(R.id.tv_action)).setText(transport.getCompanyName()+"已于"+transport.getLogLocation()+"承运");
            ((TextView) view.findViewById(R.id.tv_action_status)).setText("进行中");
            ((TextView) view.findViewById(R.id.tv_action_status)).setTextColor(getResources().getColor(R.color.app_color_blue_2));
        }
        else{
            ((TextView) view.findViewById(R.id.tv_action)).setText(transport.getCompanyName()+"已于"+transport.getLogLocation()+"承运");
            ((TextView) view.findViewById(R.id.tv_action_status)).setText("完成");
        }
        timelineLayout.setIcon(this,R.mipmap.ic_ok);
        timelineLayout.addView(view);
    }

    private void initTimeLine(List<Transport> transportList){
        for(int i=0;i<transportList.size();i++){
            initTime(i,transportList.size(),transportList.get(i));
        }
    }
    private void getProductKey(String tagId){
        OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();
        Map<String,Object> params = new HashMap<>(1);
        params.put("tagId",tagId);
        okhttpHelper.get(StringUtils.BASE_URL+"/lock/query", params, new BaseCallback<Page<Lock>>() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("F_Key", String.valueOf(e));
            }

            @Override
            public void onSuccess(@NotNull Call call, @NotNull Response response, Page<Lock> lock, int code) throws IOException {
                Log.e("R_Key", response.message());
                switch (lock.getList().get(0).lockType){
                    case "0":
                        break;
                    case "1":data = DESUtils.decode3DesBase64(data.getBytes(),lock.getList().get(0).tagPassword);
                        break;
                    default:
                        break;
                }

                try {
                    initGroupListView(data);
                }
                catch (Exception e){
                    Log.e("EXP",String.valueOf(e));
                }
            }


            @Override
            public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {
                Log.e("E_Key", "response.code:"+response.code()+"\nresponse.message:"+response.message()+"\nresult.code:"+code);
            }
        });
    }

    private void initGroupListView(String text){

        JSONObject jsonObject = JSON.parseObject(text);
        String productId = jsonObject.getString("productId");
        String productName = jsonObject.getString("productName");
        String productDate = jsonObject.getString("productDate");
        String manufacturerId = jsonObject.getString("manufacturerId");
        String productPeriod = jsonObject.getString("productPeriod");
        String productIntroduce = jsonObject.getString("productIntroduce");

        getLog(productId);

        QMUICommonListItemView item1 = showtextgroupListView.createItemView(
                ContextCompat.getDrawable(this, R.drawable.plugin_mine_user_id),
                "产品名称",
                productName,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE);

        QMUICommonListItemView item2 = showtextgroupListView.createItemView(
                ContextCompat.getDrawable(this, R.drawable.plugin_product_date),
                "生产日期",
                productDate,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE);
        QMUICommonListItemView item3 = showtextgroupListView.createItemView(
                ContextCompat.getDrawable(this, R.drawable.plugin_mine_company),
                "生产商",
                manufacturerId,
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE);
        QMUICommonListItemView item4 = showtextgroupListView.createItemView(
                ContextCompat.getDrawable(this, R.drawable.plugin_product_time),
                "保质期",
                productPeriod+"个月",
                QMUICommonListItemView.HORIZONTAL,
                QMUICommonListItemView.ACCESSORY_TYPE_NONE);

        QMUICommonListItemView item5 = showtextgroupListView.createItemView(null,
                "【产品详细】",
                productIntroduce,
                QMUICommonListItemView.VERTICAL,
                QMUICommonListItemView.ACCESSORY_TYPE_CHEVRON,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        int paddingVer = QMUIDisplayHelper.dp2px(this, 12);
        item5.setPadding(item5.getPaddingLeft(), paddingVer, item5.getPaddingRight(), paddingVer);

        int size = QMUIDisplayHelper.dp2px(this, 20);
        QMUIGroupListView.newSection(this)
                .setLeftIconSize(size, ViewGroup.LayoutParams.WRAP_CONTENT)
                .addItemView(item1, null)
                .addItemView(item2, null)
                .addItemView(item3, null)
                .addItemView(item4, null)
                .addItemView(item5, null)
                .setMiddleSeparatorInset(QMUIDisplayHelper.dp2px(this, 16), 0)
                .addTo(showtextgroupListView);
    }

}
